<?php

namespace App\Middleware;

use App\Constants\ServerCode;
use App\ENUM\ENUM_USER_STATUS;
use App\Service\ReturnMessageService;
use Hyperf\Context\ApplicationContext;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function Hyperf\Support\env;

class UserMiddleware implements MiddlewareInterface
{

    public function __construct(
        protected ContainerInterface $container,
        protected ReturnMessageService $message
    )
    {

    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //验证    时间戳   sign   应用key(public-key)  session-key
        $session_key = $request->getHeaderLine('sessionKey');
        $timestamp = $request->getHeaderLine('timestamp');
        $app_sign = $request->getHeaderLine('appSign');

        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $login_time = (int)env("LOGIN_TIME");

        if (empty($session_key) || empty($timestamp) || empty($app_sign)) {
            return $this->message->buildReturnMessage(false, '无效的请求1', ServerCode::ERROR_VALIDATE);
        }

        if (md5($timestamp.$session_key.env('APP_KEY')) != $app_sign){
            return $this->message->buildReturnMessage(false, '无效的请求2', ServerCode::ERROR_VALIDATE);
        }
        if (!$redis->exists($session_key)){
            return $this->message->buildReturnMessage(false, '无效的请求3', ServerCode::ERROR_VALIDATE);
        }
        $user_id = $redis->get($session_key);



        if (!$redis->exists('user_info_'.$user_id)){

            $get_user_where = [
                ['id','=',$user_id]
            ];
            $user_message = $this->user_dao->getUserFirst($get_user_where);
            if (empty($user_message)){
                return ['status'=>false,'message'=>'账号错误',ServerCode::ERROR_VALIDATE];
            }


            $redis->set('user_info_'.$user_id,json_encode($user_message));
            $redis->expire('user_info_'.$user_id,$login_time);

            $redis->expire($session_key,$login_time);

            $redis->expire('user_sessionKey_'.$user_id,$login_time);


        }else{

            $user_info = $redis->get('user_info_'.$user_id);
            $user_message = json_decode($user_info, true);
            $redis->expire('user_sessionKey_'.$user_id,$login_time);

            //保存用户id
            $redis->expire($session_key,$login_time);

            //更新用户信息
            $redis->expire('user_info_'.$user_id,$login_time);
        }

        if ($user_message['status'] == ENUM_USER_STATUS::STOP){
            return ['status'=>false,'message'=>'账号被封禁',ServerCode::ERROR_VALIDATE];
        }


        return $handler->handle($request);
    }

}